import Utils from '../utils/Common'

class _Directive {
  bind(el, binding) {
    const userInfo = Utils.GetLoginUserInfo()
    if (Utils.IsEmpty(userInfo)) {
      el.style.display = 'none'
      return
    }
    const userId = el.dataset.userid
    const role = el.dataset.role
    if (binding.value.includes('business_user::edit')) {
      console.log(role)
    }
    if (!Utils.IsEmpty(userId) && binding.value.includes('business_user') && userInfo.id === +userId) {
      el.style.display = 'none'
    }
    if (!Utils.IsEmpty(role) && binding.value.includes('business_user') && (+role > +userInfo.role)) {
      el.style.display = 'none'
    }
    if (!Utils.IsEmpty(userInfo) && +userInfo.role === 5) {
      // el.style.display = 'none'
      return
    }
    const UserPermissions = userInfo.Permissions.map(p => p.page + '::' + p.key)
    if (!UserPermissions.includes(binding.value)) {
      el.style.display = 'none'
    }
    // 调用update方法进行初始的权限判断和元素显示状态设置
    this.update(el, binding, UserPermissions)
  }

  update(el, binding, UserPermissions) {
    const userInfo = Utils.GetLoginUserInfo()
    if (!UserPermissions) {
      // 如果UserPermissions未传入（比如初次绑定后后续更新时可传入已有的），重新获取
      UserPermissions = userInfo.Permissions.map(p => p.page + '::' + p.key)
    }
    console.log(binding.value, UserPermissions.includes(binding.value))
    if (!UserPermissions.includes(binding.value)) {
      el.style.display = 'none'
    } else {
      // 如果有权限，显示元素（恢复显示，防止之前隐藏了后续有权限却没显示出来）
      el.style.display = ''
    }
    const userId = el.dataset.userid
    const role = el.dataset.role
    if (binding.value.includes('business_user::edit')) {
      console.log(role)
    }
    if (!Utils.IsEmpty(userId) && binding.value.includes('business_user') && userInfo.id === +userId) {
      el.style.display = 'none'
    }
    if (!Utils.IsEmpty(role) && binding.value.includes('business_user') && (+role > +userInfo.role)) {
      el.style.display = 'none'
    }
  }
}

export default {
  permission: new _Directive().bind.bind(new _Directive())
}
